package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/", "/index.html", "index"})
    public String indexPage(Model model) {
//        prefix: classpath:/templates/
//        suffix: .html
        //视图解析器进行拼串
        //classpath:/templates/ + 返回值 + .html

        //TODO 1、查出所有的一级分类
        List<CategoryEntity> categoryEntityList = categoryService.getLevel1Categories();
        model.addAttribute("categorys", categoryEntityList);
        return "index";
    }

    /**
     * 路径：/index/catalog.json
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJSON() {
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJSON();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //1、获取一把锁，只要锁的名字一样，那就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");
        //2、加锁，默认加的锁都是30s
        //阻塞式等待
        //锁的自动续期，如果业务运行时间超长，运行期间会给锁续上新的30s，不用担心业务时间长，锁自动被删掉
        //加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁也会默认在30s后自动删除
        lock.lock();
        //10秒自动解锁，自动解锁时间一定要大于业务的执行时间
        //问题：lock.lock(10, TimeUnit.SECONDS) 锁超时不会自动续期
        //1、如果我们传递了锁的超时时间，就发送给redis执行脚本进行占锁，默认超时就是我们指定的时间
        //2、如果未指定锁的超时时间，就是用30 * 1000 [lockWatchdogTimeout]
        //  只要占锁成功，就会启动定时任务【重新给锁设置过期时间，新的过期时间就是看门狗的默认过期时间】
        //  续期事件是10秒左右：【internalLockLeaseTime / 3, TimeUnit.MILLISECONDS】
//        lock.lock(10, TimeUnit.SECONDS);

        //最佳实践
        //lock.lock(30, TimeUnit.SECONDS);省掉了整个续期操作，手动解锁
        try {
            System.out.println("加锁成功，执行业务，线程ID:" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //3、解锁
            //假设解锁代码没有运行，redisson会不会出现死锁
            System.out.println("释放锁，线程ID:" + Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }


    /**
     * 读写锁
     * 读锁能保证一定能读到最新数据，修改期间，写锁是一个排他锁（互斥锁）
     * 读锁是一个共享锁
     * 写锁没释放，读就必须等待
     * 读+读：相当于无锁，并发度，只会在redis中记录好当前的读锁，他们都会同时加锁成功
     * 写+写：阻塞释放
     * 写+读：等待写锁释放
     * 读+写：等待读释放，有读锁，写也需要等待
     * 只要有写的存在，都必须等待
     */
    @ResponseBody
    @GetMapping("/write")
    public String writeValue() {
        //1、分布式读写锁
        //改数据加写锁，读数据加读锁
        String uuid = "";
        RReadWriteLock rwlock = redissonClient.getReadWriteLock("rw-lock");
        try {
            RLock rLock = rwlock.writeLock();
            boolean res = rLock.tryLock(100, 50, TimeUnit.SECONDS);
            if (res) {
                System.out.println("写锁加锁成功" + Thread.currentThread().getId());
                try {
                    uuid = UUID.randomUUID().toString();
                    Thread.sleep(30 * 1000);
                    stringRedisTemplate.opsForValue().set("writeValue", uuid);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    rLock.unlock();
                    System.out.println("写锁释放" + Thread.currentThread().getId());
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("write --- writeValue ====>" + uuid);
        return uuid;
    }

    @ResponseBody
    @GetMapping("/read")
    public String readValue() {
        String writeValue = "";
        RReadWriteLock rwlock = redissonClient.getReadWriteLock("rw-lock");
        try {
            //加读锁
            RLock rLock = rwlock.readLock();
//            rLock.lock();
            boolean res = rLock.tryLock(100, 50, TimeUnit.SECONDS);
            if (res) {
                System.out.println("读锁加锁成功" + Thread.currentThread().getId());
                try {
                    Thread.sleep(30 * 1000);
                    writeValue = stringRedisTemplate.opsForValue().get("writeValue");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    rLock.unlock();
                    System.out.println("读锁释放" + Thread.currentThread().getId());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("read --- writeValue ====>" + writeValue);
        return writeValue;
    }

    /**
     * 车库停车
     * 3车位
     * 信号量也可以用作分布式限流
     */
    @ResponseBody
    @GetMapping("park")
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        //获取一个信号，获取一个值，占一个车位
//        park.acquire();
        boolean b = park.tryAcquire();
        if (b) {
            //执行业务
        } else {
            return "error";
        }
        return "ok=>" + b;
    }

    /**
     * 车库停车
     * 3车位
     */
    @ResponseBody
    @GetMapping("go")
    public String go() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        //释放一个车位
        park.release();
        return "ok";
    }

    /**
     * 放假，锁门
     * 1班没人了
     * 2班没人了
     * ...
     * 10班没人了
     * 10个班都走完，可以锁大门
     */
    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        //设置等待10个班的人都走完
        door.trySetCount(10);

        //等待闭锁都完成
        boolean await = door.await(300, TimeUnit.SECONDS);
        if (await) {
            return "放假了...";
        } else {
            return "人还没走完呢...";
        }
    }

    @ResponseBody
    @GetMapping("/gogogo/{classid}")
    public String gogogo(@PathVariable(name = "classid", required = true) Long classid) {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        //计数减1
        door.countDown();

        return classid + "班的人都走了...";
    }
}
